﻿using System;
using System.Collections;
using System.Data.Linq.Mapping;
using System.Runtime.Serialization;
using Portal.Data.Helper;
using Portal.Core.Binding.FormBuilder;
using Portal.Core.Helper;

namespace Portal.Data.Entity
{
    [Table(Name = "dbo.Banner"), Serializable, DataContractAttribute]
    public class Banner : BaseObject
    {

        #region Properties
        public int ID { get { return Banner_ID; } set { Banner_ID = value; } }

        [SkipBinding]
        [Column(Name = "Banner_ID", IsPrimaryKey = true, IsDbGenerated = true)]
        public int Banner_ID { get; set; }

        [ColumnAttribute(Name = "Name"), Validator(Required = true)]
        public string Name { get; set; }

        [ColumnAttribute(Name = "Path"), Builder(Title = "Banner Ảnh/Flash", DataType = DataType.Image), Image(SavePath = "Images/Banners/")]
        public string Path { get; set; }

        [ColumnAttribute(Name = "CompanyName")]
        public string CompanyName { get; set; }

        [ColumnAttribute(Name = "Address")]
        public string Address { get; set; }

        [ColumnAttribute(Name = "CustomerName"), Validator(Required = true)]
        public string CustomerName { get; set; }

        [ColumnAttribute(Name = "Emails"), Validator(Required = true, RegMessage = "Invalid email address(s)", RegularExpression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(;\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*")]
        public string Emails { get; set; }

        [ColumnAttribute(Name = "Notify")]
        public bool? Notify { get; set; }

        [ColumnAttribute(Name = "NotifyDate")]
        public DateTime? NotifyDate { get; set; }

        [ColumnAttribute(Name = "ExpireDate")]
        public DateTime? ExpireDate { get; set; }

        [ColumnAttribute(Name = "Fax")]
        public string Fax { get; set; }

        [ColumnAttribute(Name = "Telphone")]
        public string Telphone { get; set; }

        [ColumnAttribute(Name = "Mobile")]
        public string Mobile { get; set; }

        [ColumnAttribute(Name = "Width"), Validator(Required = true, RangeMessage = "Out of range", Min = 0, Max = 10000)]
        public int? Width { get; set; }

        [ColumnAttribute(Name = "Height"), Validator(Required = true, RangeMessage = "Out of range", Min = 0, Max = 10000)]
        public int? Height { get; set; }

        [ColumnAttribute(Name = "URL")]
        public string URL { get; set; }

        [ColumnAttribute(Name = "DisplayText"), Builder(Title = "Banner chữ"), Validator(MaxLength = 500, RegMessage = "Tối đa 500 ký tự")]
        public string DisplayText { get; set; }

        [ColumnAttribute(Name = "Status"), Builder(Title = "Kích hoạt?")]
        public bool Status { get; set; }

        [ColumnAttribute(Name = "Clicked"), SkipBinding]
        public int Clicked { get; set; }

        [ColumnAttribute(Name = "IsText"), SkipBinding]
        public bool IsText { get; set; }


        #endregion

        #region Extension Prop
        public string RenderImage
        {
            get
            {
                if (IsText)
                    return string.Format("<a href='{0}' target=_blank>{1}</a>", URL, DisplayText);
                return ImageHelper.RenderImageFlash(Path, 250, 100);
            }
        }
        public string Display
        {
            get
            {
                return DisplayHtml(0, 0);
            }
        }
        #endregion

        #region Methods
        public static Banner FindByPrimaryKey(object objectid)
        {
            return FindByPrimaryKey<Banner>(objectid);
        }
        public static IList ListAll()
        {
            //getcache  -----------------------
            var parameter = new object[] { typeof(Banner).Name, "ListAll" };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj != null)
                return (IList)obj;
            //end get cache -------------------

            var value = LINQHelper.GetList<Banner>("select * from Banner");

            CacheHelper.Instance.Set(parameter, value);
            return value;
        }
        public static IList FindByPosition(int position)
        {
            var parameter = new object[] { typeof(Banner).Name, "FindByPosition", position };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj != null)
                return (IList)obj;

            const string sql = "select o.*,oo.Sort from Banner o INNER JOIN BannerGroup oo ON o.Banner_ID=oo.Banner_Id where o.Status={0} and oo.Group_Id={1} order by oo.Sort";
            var result = LINQHelper.GetList<Banner>(sql, true, position);
            CacheHelper.Instance.Set(parameter, result);
            return result;
        }
        public static IList Paging(int pagesize, int pageindex, out int count)
        {
            var parameter = new object[] { typeof(Banner).Name, "Paging", pagesize, pageindex };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj != null)
            {
                var values = (object[])obj;
                count = (int)values[1];
                return (IList)values[0];
            }

            //end get cache -------------------
            const string hql = "select * from Banner";
            const string order = "order by Banner_ID desc";
            var list = LINQHelper.SlicedFindAll<Banner>(hql, order, pageindex * pagesize, pagesize, out count);
            var newvalues = new object[] { list, count };
            CacheHelper.Instance.Set(parameter, newvalues);

            return list;
        }
        #endregion Methods

        #region Logic
        /// <summary>
        /// Get Image or Flash html code. If ignore size, input 0 value for W/H
        /// </summary>
        /// <returns></returns>
        public string DisplayHtml(int width, int height, bool activeURL, bool newWindow)
        {
            var parameter = new object[] { typeof(Banner).Name, "DisplayHtml", width, height, activeURL, newWindow, ID };
            var obj = CacheHelper.Instance.Get(parameter);
            if (obj == null)
            {
                if (Notify.Value && ExpireDate <= DateTime.Now)
                {
                    SendExpiredMail(this);
                    return "Ảnh/Flash này đã hết thời gian đăng ký.";
                }

                var sb = new System.Text.StringBuilder();

                if (Notify.Value && NotifyDate < DateTime.Now)
                {
                    SendNotifyMail(this);
                    sb.Append("Ảnh/Flash này sắp hết thời gian đăng ký.");
                }

                if (activeURL && !string.IsNullOrEmpty(URL))
                {
                    string fullUrl = URL;
                    if (!fullUrl.StartsWith("http"))
                        fullUrl = "http://" + URL;
                    sb.Append(String.Format("<div class='onclick' onclick=\"javascript:open_link('{0}','{1}')\">",
                                            fullUrl, newWindow));
                }
                else
                    sb.Append("<div>");

                int w = width;
                int h = height;
                if (width <= 0 && height <= 0)
                {
                    w = Width.Value;
                    h = Height.Value;
                }
                sb.Append(ImageHelper.RenderImageFlash(Path, w, h));

                sb.Append("</div>");

                CacheHelper.Instance.Set(parameter, sb.ToString());

                return sb.ToString();
            }
            return obj.ToString();
        }

        public string DisplayHtml(int width, int height)
        {
            return DisplayHtml(width, height, false, false);
        }

        private void SendExpiredMail(Banner banner)
        {

        }

        private void SendNotifyMail(Banner banner)
        {

        }
        #endregion
    }
}
